<?php
require_once BASEPATH.'/libraries/Model.php';

/**
 * Base Models
 * @author cuonglv@vietincom.com
 */
class BaseModel extends Model{
	protected  $_key = null; // primary key of table

	protected $_tableName = null;

	protected function  __construct()
	{
		parent::Model();
	}

	public function _insert($obj)
	{
    	try
		{
    		$this->db->insert($this->_tableName, $obj);
    		$id = $this->db->insert_id();

    		return $id;

    	}
    	catch(Exception $ex)
		{
			throw $ex->getMessage();
    	}
    }

	public function _update($obj)
	{
		try
		{
			$key = $obj->_key;
			unset($obj->_key);
			$this->db->update($this->_tableName, $obj, array("$this->_key" => $key));

    		return $key;
		}
		catch(Exception $ex)
		{
			throw $ex->getMessage();
    	}
    }

	public function _delete($value, $section = null)
	{
		try
		{			
			if($section != null)
				$this->db->delete($this->_tableName, array("$section" => $value));
			else
				$this->db->delete($this->_tableName, array("$this->_key" => $value));
    	}
    	catch(Exception $ex)
		{
			throw $ex->getMessage();
    	}
    }

	public function _getByKey($value)
	{
		try
		{
			$sql = "SELECT
						*
					FROM
						`$this->_tableName`
					WHERE
						`$this->_key` = '$value'";
			$data = $this->db->query($sql);

			return $data->result();
		}
		catch(Exception $ex)
		{
			throw $ex->getMessage();
    	}
	}

    public function _getAll()
    {
        try
        {
            $sql = "SELECT
						*
					FROM
						`$this->_tableName`
					WHERE
						1";
			$data = $this->db->query($sql);
            return $data->result();
        }
        catch(Exception $ex)
        {
            throw  $ex->getMessage();
        }
    }
}
?>
